package com.cy.oa.service.impl;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.impl.identity.Authentication;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.cy.oa.entity.LeaveBean;
import com.cy.oa.mapper.LeaveMapper;
import com.cy.oa.service.LeaveService;
import com.cy.system.annotation.DataSource;
import com.cy.system.config.DataSourceContextHolder;
import com.cy.system.entity.User;

@Service
public class LeaveServiceImpl implements LeaveService{
	@Resource
	LeaveMapper leaveMapper;
	@Resource
	RuntimeService runtimeService;
	@Resource
	TaskService taskService;

	@Override
	/*@DataSource(dataSourceType="activitiDataSource")*/  //这样切换数据源无效，因为加了事务
	@Transactional(isolation=Isolation.DEFAULT,propagation=Propagation.REQUIRED)
	public boolean applyLeave(LeaveBean leave,String outcome) {
		HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
		HttpSession session = request.getSession();
		User user = (User)session.getAttribute("userSession");
		leave.setLeaveUserId(user.getUserId());
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH-mm-ss");
		leave.setApplyTime(sdf.format(new Date()));
		leave.setLeaveUserName(user.getUserName());
		System.out.println("outcomeApply"+outcome);
		/*DataSourceContextHolder.setDbType("activitiDataSource");*/ //这样切换数据源无效，因为加了事务
		int resInt = leaveMapper.addLeave(leave);
		/*DataSourceContextHolder.clearDbType();*/
		
		System.out.println(leave.getLeaveId());
		String leaveProcessKey = leave.getClass().getSimpleName();
		String businessKey = leaveProcessKey+"."+leave.getLeaveId();
		HashMap<String,Object> variables = new HashMap<String,Object>();
		variables.put("userId", user.getUserId());
		ProcessInstance processInstance = runtimeService.startProcessInstanceByKey(leaveProcessKey, businessKey, variables);
		leave.setProcessInstanceId(processInstance.getProcessInstanceId());
		leave.setLeaveState(1);
		//更新请假单processInstanceId
		//更新请假单state
		leaveMapper.updateLeaveBeanById(leave);
		Task task = taskService.createTaskQuery().taskAssignee(Integer.toString(user.getUserId()))
				                 .orderByTaskCreateTime().desc().list().get(0);
		this.completeLeave(task.getId(), outcome, null,null);
		
		if(resInt==1) {
			return true;
		}
		return false;
	}

	@Override
	@Transactional(isolation=Isolation.DEFAULT,propagation=Propagation.REQUIRED)
	public boolean completeLeave(String taskId, String outcome, String commentMsg,String leaveId) {
		//1、确定流程走向
		HashMap<String,Object> variables = new HashMap<String,Object>(); 
		System.out.println("outcomeService:"+outcome);
		variables.put("outcome", outcome);
		System.out.println("outcome:"+outcome);
		System.out.println("taskId:"+taskId);
		//2、获取任务对象、设置Authentication
		HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
		HttpSession session = request.getSession();
		User user = (User)session.getAttribute("userSession");
		Authentication.setAuthenticatedUserId(user.getUserName());
		Task task = taskService.createTaskQuery().taskId(taskId).singleResult();
		//3、获取流程实例Id
		System.out.println("task:"+task);
		String processInstanceId = task.getProcessInstanceId();
		//4、处理comment
		if(null!=commentMsg) {
			taskService.addComment(taskId, processInstanceId, commentMsg);
		}
		//5、完成任务
		taskService.complete(taskId, variables);
		//6、判断任务是否结束，更新请假单状态
		ProcessInstance pIT = runtimeService.createProcessInstanceQuery().processInstanceId(processInstanceId).singleResult();
		if(null==pIT) {
			LeaveBean leaveBean = new LeaveBean();
			leaveBean.setLeaveId(Integer.parseInt(leaveId));
			leaveBean.setLeaveState(2);
			leaveMapper.updateLeaveBeanById(leaveBean);
		}
		return true;
	}

	@Override
	@DataSource(dataSourceType="activitiDataSource")
	public LeaveBean queryLeaveByInstanceId(String instanceId) {
		
		return leaveMapper.queryLeaveByInstanceId(instanceId);
	}

	@Override
	public int updateLeaveBeanById(LeaveBean leaveBean) {
		
		return leaveMapper.updateLeaveBeanById(leaveBean);
	}

	@Override
	@DataSource(dataSourceType="activitiDataSource")
	public List<LeaveBean> queryAllLeave() {
		return leaveMapper.queryAllLeave();
	}

	

	
}
